package com.glory.good_dark.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.good_dark.R;
import com.glory.good_dark.adapter.CheckShowListAdapter;
import com.glory.good_dark.adapter.ShowCheckImageListAdapter;
import com.glory.good_dark.application.App;
import com.glory.good_dark.entity.CheckShowEntity;
import com.glory.good_dark.entity.response.BaseEntity;
import com.glory.good_dark.utils.DateUtils;
import com.glory.good_dark.utils.DeviceUtil;
import com.glory.good_dark.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.activity_public.FreeUI_CameraActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_FileUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * FileName: ShowCheckActivity
 * Author: XJH
 * Date: 2020/4/3 13:54
 * Description: 点检执行
 * History:
 */
public class ShowCheckActivity extends BaseProjectActivity {


    @BindView(R.id.tvPosition)
    TextView tvPosition;
    @BindView(R.id.tvProjectName)
    TextView tvProjectName;
    @BindView(R.id.etValue)
    FreeUI_ClearEditText etValue;
    @BindView(R.id.tvValues)
    TextView tvValues;
    @BindView(R.id.ivValueArrow)
    ImageView ivValueArrow;
    @BindView(R.id.flValueList)
    FrameLayout flValueList;
    @BindView(R.id.tvValue)
    TextView tvValue;
    @BindView(R.id.etRemarks)
    FreeUI_ClearEditText etRemarks;
    @BindView(R.id.tvRemarks)
    TextView tvRemarks;
    @BindView(R.id.tvExecute)
    TextView tvExecute;
    @BindView(R.id.tvConfirm)
    TextView tvConfirm;
    @BindView(R.id.ivConfirm)
    ImageView ivConfirm;
    @BindView(R.id.rvCheckDescList)
    RecyclerView rvCheckDescList;
    @BindView(R.id.rvIconList)
    RecyclerView rvIconList;
    @BindView(R.id.btnSubmit)
    Button btnSubmit;
    @BindView(R.id.btnSave)
    Button btnSave;
    @BindView(R.id.BtnCancel)
    Button BtnCancel;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private String tableName = "";
    private String guid = "";
    private CheckShowListAdapter checkShowListAdapter;
    private File mFilePath;
    private ShowCheckImageListAdapter showCheckImageListAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_show_check;
    }

    @Override
    protected void initView() {
        tableName = getIntent().getExtras().getString("tableName");
        guid = getIntent().getExtras().getString("GUID");
        if (getIntent().getExtras().getBoolean("checkState")) {
            btnSave.setVisibility(View.GONE);
            btnSubmit.setVisibility(View.GONE);
        }
        initRecyclerView(rvCheckDescList, this);
        checkShowListAdapter = new CheckShowListAdapter(null);
        checkShowListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        checkShowListAdapter.isFirstOnly(true);
        rvCheckDescList.setAdapter(checkShowListAdapter);
        checkShowListAdapter.setCheckID(guid);
        initGridRecyclerView(rvIconList,this,3);
        mFilePath = FreeApi_FileUtils.setCreatPath(FreeApi_FileUtils.setCreatPath(
                DateUtils.getNowDate("yyyyMMdd"), "GOODDARK" + DateUtils.getNowDate("yyyyMM")), "CHECK");
        showCheckImageListAdapter = new ShowCheckImageListAdapter(null);
        rvIconList.setAdapter(showCheckImageListAdapter);
        showCheckImageListAdapter.addData("");
        showCheckImageListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (showCheckImageListAdapter.getData().get(position).equals("") && position == 0){
                    //拍照
                    takeCamera();
                }else {
                    //预览
                    showPicture(showCheckImageListAdapter.getData().get(position));
                }
            }
        });

        showCheckImageListAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                if (showCheckImageListAdapter.getData().get(position).equals("") && position == 0){
                }else {
                    //delete
                    showCheckImageListAdapter.remove(position);
                }
                return true;
            }
        });
    }

    private void showPicture(String picPath) {
        if (!TextUtils.isEmpty(picPath)) {
            if (picPath.contains("GOODDARK")) {
                if (FreeApi_FileUtils.isFile(picPath)) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 1);
                    ArrayList<String> strings = new ArrayList<>();
                    strings.add(picPath);
                    bundle.putStringArrayList("data", strings);
                    FreeApi_Utils.skipWithExtraIntent("", bundle,ShowCheckActivity.this, ShowBigPictureActivity.class);
                } else {
                    showToast("照片文件出错", false);
                }
            } else {
                Bundle bundle = new Bundle();
                bundle.putInt("type", 0);
                ArrayList<String> strings = new ArrayList<>();
                strings.add(picPath);
                bundle.putStringArrayList("data", strings);
                FreeApi_Utils.skipWithExtraIntent("", bundle,ShowCheckActivity.this, ShowBigPictureActivity.class);
            }
        } else {
            showToast("没有拍照", false);
        }
    }

    private void takeCamera() {
        new RxPermissions(this)
                .requestEachCombined(Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO)
                .subscribe(permission -> {
                    if (permission.granted){
                        //同意权限
                        FreeUI_CameraActivity.goCameraActivity(ShowCheckActivity.this, mFilePath.getPath(),
                                100,
                                false);
                    }else if(permission.shouldShowRequestPermissionRationale){
                        //用户拒绝了该权限，没有选中『不再询问』
                        showToast("当前权限开启失败，请重试",false);
                    }else {
                        //用户拒绝了权限
                        showToast("当前权限开启失败，并且设置为不再询问，请去设置页面重新开启!",false);
                    }
                });
    }

    @Override
    protected void initData() {
//        String ss = "{\"data\":{\"BODY\":{\"CHECK_ID\":\"1e911651-d332-48f5-86f0-27ea3b19441d\",\"PARAMETER_TYPE_LIST\":[{\"PARAMETER_TYPE_NAME\":\"输入框\"},{\"PARAMETER_TYPE_NAME\":\"选择框\"}],\"CHECK_PAM_LIST\":[{\"CHECK_NAME\":\"DA测试表单\",\"PARAMETER_NAME\":\"顶针尺寸\",\"CHECK_N0\":\"1\",\"SVID\":null},{\"CHECK_NAME\":\"DA测试表单\",\"PARAMETER_NAME\":\"Bond Force\",\"CHECK_N0\":\"2\",\"SVID\":\"874\"},{\"CHECK_NAME\":\"DA测试表单\",\"PARAMETER_NAME\":\"吸嘴尺寸\",\"CHECK_N0\":\"3\",\"SVID\":null},{\"CHECK_NAME\":\"DA测试表单\",\"PARAMETER_NAME\":\"Pre Heat Delay\",\"CHECK_N0\":\"4\",\"SVID\":\"822\"}],\"CHECK_ITEM_LIST\":[{\"PARAMETER_NAME\":\"顶针尺寸\",\"CREATOR\":\"Admin\",\"CREATED_TIME\":\"2020/12/22 22:15:39\",\"UPDATOR\":\"\",\"UPDATED_TIME\":\"\",\"PARAMETER_TYPE\":\"输入框\",\"DESCRIPTION\":\"\",\"EQP_CAPA\":\"\",\"EQP_NO\":\"\",\"PMS_CHEDULE_NAME\":\"\",\"CHECKLIST_NAME\":\"DA测试表单\",\"TOP_LIMIT\":\"999999999\",\"BOTTOM_LIMIT\":\"0\",\"CHECK_N0\":\"0\"},{\"PARAMETER_NAME\":\"Bond Force\",\"CREATOR\":\"\",\"CREATED_TIME\":\"\",\"UPDATOR\":\"\",\"UPDATED_TIME\":\"\",\"PARAMETER_TYPE\":\"输入框\",\"DESCRIPTION\":\"\",\"EQP_CAPA\":\"AD838\",\"EQP_NO\":\"DA113\",\"PMS_CHEDULE_NAME\":\"\",\"CHECKLIST_NAME\":\"DA测试表单\",\"TOP_LIMIT\":\"0\",\"BOTTOM_LIMIT\":\"0\",\"CHECK_N0\":\"0\"},{\"PARAMETER_NAME\":\"吸嘴尺寸\",\"CREATOR\":\"Admin\",\"CREATED_TIME\":\"2020/12/22 22:15:06\",\"UPDATOR\":\"\",\"UPDATED_TIME\":\"\",\"PARAMETER_TYPE\":\"输入框\",\"DESCRIPTION\":\"\",\"EQP_CAPA\":\"\",\"EQP_NO\":\"\",\"PMS_CHEDULE_NAME\":\"\",\"CHECKLIST_NAME\":\"DA测试表单\",\"TOP_LIMIT\":\"9999999\",\"BOTTOM_LIMIT\":\"0\",\"CHECK_N0\":\"0\"},{\"PARAMETER_NAME\":\"Pre Heat Delay\",\"CREATOR\":\"\",\"CREATED_TIME\":\"\",\"UPDATOR\":\"\",\"UPDATED_TIME\":\"\",\"PARAMETER_TYPE\":\"输入框\",\"DESCRIPTION\":\"\",\"EQP_CAPA\":\"AD838\",\"EQP_NO\":\"DA113\",\"PMS_CHEDULE_NAME\":\"\",\"CHECKLIST_NAME\":\"DA测试表单\",\"TOP_LIMIT\":\"0\",\"BOTTOM_LIMIT\":\"0\",\"CHECK_N0\":\"0\"}],\"CHECK_HIS_DATA_LIST\":[{\"ID\":0.0,\"DESCRIPTION\":null,\"CREATOR\":null,\"CREATED_TIME\":null,\"UPDATOR\":null,\"UPDATED_TIME\":null,\"CHECK_NAME\":null,\"CHECKID\":null,\"PARAMETER_NAME\":\"顶针尺寸\",\"SVID\":null,\"PARAMETER_VALUE\":null,\"OPERATOR\":null,\"CONFIRM_PERSON\":null},{\"ID\":0.0,\"DESCRIPTION\":null,\"CREATOR\":null,\"CREATED_TIME\":null,\"UPDATOR\":null,\"UPDATED_TIME\":null,\"CHECK_NAME\":null,\"CHECKID\":null,\"PARAMETER_NAME\":\"Bond Force\",\"SVID\":\"874\",\"PARAMETER_VALUE\":\"80\",\"OPERATOR\":null,\"CONFIRM_PERSON\":null},{\"ID\":0.0,\"DESCRIPTION\":null,\"CREATOR\":null,\"CREATED_TIME\":null,\"UPDATOR\":null,\"UPDATED_TIME\":null,\"CHECK_NAME\":null,\"CHECKID\":null,\"PARAMETER_NAME\":\"吸嘴尺寸\",\"SVID\":null,\"PARAMETER_VALUE\":null,\"OPERATOR\":null,\"CONFIRM_PERSON\":null},{\"ID\":0.0,\"DESCRIPTION\":null,\"CREATOR\":null,\"CREATED_TIME\":null,\"UPDATOR\":null,\"UPDATED_TIME\":null,\"CHECK_NAME\":null,\"CHECKID\":null,\"PARAMETER_NAME\":\"Pre Heat Delay\",\"SVID\":\"822\",\"PARAMETER_VALUE\":null,\"OPERATOR\":null,\"CONFIRM_PERSON\":null}]},\"HEADER\":{\"MACHINENAME\":\"MI 9\",\"MESSAGENAME\":\"PDAGetExecuteCheckInfo\",\"TRANSACTIONID\":\"ac686ae2-6c97-412b-89ff-dc4dd7536b0c\",\"EVENTTIME\":\"2021-08-03 21:42:37\"},\"RETURN\":{\"RETURNCODE\":0,\"RETURNMESSAGE\":\"请求成功！\"}}}";
//        BaseEntity<CheckShowEntity> bean = (new Gson()).fromJson(ss, new TypeToken<BaseEntity<CheckShowEntity>>() {}.getType());
//        List<CheckShowEntity.CheckPam> checkPamList = bean.getData().getBody().getCHECK_PAM_LIST();
//        if (checkPamList.size() > 0){
//            checkShowListAdapter.setCheckNameList(bean.getData().getBody().getCHECK_ITEM_LIST());
//            checkShowListAdapter.setCheckValueList(bean.getData().getBody().getCHECK_HIS_DATA_LIST());
//            checkShowListAdapter.setNewData(checkPamList);
//        }
        FreeUI_EntityCallBack<BaseEntity<CheckShowEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<CheckShowEntity>>
                (new TypeToken<BaseEntity<CheckShowEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<CheckShowEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), getSupportFragmentManager())) {
                    List<CheckShowEntity.CheckPam> checkPamList = response.body().getData().getBody().getCHECK_PAM_LIST();
                    if (checkPamList.size() > 0) {
                        checkShowListAdapter.setCheckNameList(response.body().getData().getBody().getCHECK_ITEM_LIST());
                        checkShowListAdapter.setCheckValueList(response.body().getData().getBody().getCHECK_HIS_DATA_LIST());
                        checkShowListAdapter.setNewData(checkPamList);
                    }
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<CheckShowEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDAGetExecuteCheckInfo");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("CHECK_ID", guid);
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDAGetExecuteCheckInfo", map);
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(tableName);
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    @Override
    protected void EQPReplaceSuccess(int tag, String content) {

    }


    @OnClick({R.id.btnSubmit, R.id.btnSave, R.id.BtnCancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnSubmit:
                if (checkShowListAdapter.getOutData().size() > 0) {
                    showToast("含有超限数值", false);
                    return;
                }

                List<CheckShowEntity.CheckPam> data = checkShowListAdapter.getData();
                for (CheckShowEntity.CheckPam checkPam : data) {
                    if (checkPam.getPARAMETER_VALUE().equals("") || checkPam.getOPERATOR().equals("") || checkPam.getCONFIRM_PERSON().equals("")) {
                        showToast("数据有空值", false);
                        return;
                    }
                }
                submit();
                break;
            case R.id.btnSave:
                if (checkShowListAdapter.getOutData().size() > 0) {
                    showToast("含有超限数值", false);
                    return;
                }
                submit();
                break;
            case R.id.BtnCancel:
                finish();
                break;
        }
    }


    private void submit() {
        FreeUI_EntityCallBack<BaseEntity<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<JSONObject>>
                (new TypeToken<BaseEntity<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<JSONObject>> response) {
                if (response.body().isSuccess(getApplicationContext(), getSupportFragmentManager())) {
                    showConfirmDialog(ShowCheckActivity.this, "提交成功");
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "PDASaveExecuteCheckInfo");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("CHECK_ID", guid);
        map.add("PICTRRUELIST", new JsonParser().parse(new Gson().toJson(getPicData())).getAsJsonArray());
        map.add("CHECK_HIS_DATA_LIST", new JsonParser().parse(new Gson().toJson(checkShowListAdapter.getData())).getAsJsonArray());
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDASaveExecuteCheckInfo", map);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101) {
            if (data == null){
                return;
            }
            String path = data.getStringExtra("path");
            if (path.contains(".mp4")){
                showToast("当前不支持视频,请重新选择!",false);
                return;
            }
            showCheckImageListAdapter.addData(path);
//            showToast(path,true);
        }
    }

    private List<PictureInfo> getPicData(){
        List<PictureInfo> pic = new ArrayList<>();
        if (showCheckImageListAdapter.getData().size() > 1) {
            List<String> data = showCheckImageListAdapter.getData();
            data.remove(0);
            for (String s : data){
                byte[] bytes = DeviceUtil.readStream(s);
                pic.add(new PictureInfo(bytes));
            }
        }
        return pic;
    }

    public class PictureInfo implements Serializable{
        private byte[] pictruevalue;

        public PictureInfo(byte[] pictruevalue) {
            this.pictruevalue = pictruevalue;
        }

        public byte[] getPictruevalue() {
            return pictruevalue;
        }

        public void setPictruevalue(byte[] pictruevalue) {
            this.pictruevalue = pictruevalue;
        }
    }
}
